package com.nowcoder.community.controller;

import com.nowcoder.community.annotation.LoginRequired;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.util.CommunityUtil;
import com.nowcoder.community.util.HostHolder;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;

@Controller
@Slf4j
@RequestMapping(path = "/user")
public class UserController {

    @Value("${community.path.upload}")
    private String uploadPath;
    @Value("${community.path.domain}")
    private String domain;
    @Value("${server.servlet.context-path}")
    private String contextPath;
    @Autowired
    UserService userService;
    @Autowired
    HostHolder holder;

    /**
     * 设置页面
     * @return
     */
    @LoginRequired
    @RequestMapping(path = "setting",method = RequestMethod.GET)
    public String getSettingPage(){
        return "/site/setting";
    }

    /**
     * 头像上传
     * @param imageFile
     * @param model
     * @return
     */
    @LoginRequired
    @RequestMapping(path = "upload", method = RequestMethod.POST)
    public String uploadHeader(MultipartFile imageFile, Model model){
        if (imageFile == null){
            model.addAttribute("error", "图片不存在");
            return "/site/setting";
        }
        String originalFilename = imageFile.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        if(StringUtils.isBlank(suffix)){
            model.addAttribute("error", "格式不正确");
            return "/site/setting";
        }
        //生成随机文件名
        originalFilename = CommunityUtil.generateUUID() + suffix;
        //确定文件路径
        File dest = new File(uploadPath + "/" + originalFilename);
        try {
            imageFile.transferTo(dest);
        } catch (IOException e) {
            log.error("文件上传失败");
            throw new RuntimeException("文件上传失败",e);
        }
        User user = holder.getUser();
        String headerUrl = domain + contextPath + "/user/header/" + originalFilename;
        userService.updateHeader(user.getId(),headerUrl);
        return "redirect:/index";
    }

    /**
     * 得到头像
     * @param fileName
     * @param response
     */
    @RequestMapping(path = "/header/{fileName}",method = RequestMethod.GET)
    public void getHeader(@PathVariable("fileName") String fileName, HttpServletResponse response){
       //路径
        fileName = uploadPath + "/" + fileName;
        //文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf(".")+1);
        response.setContentType("image/" + suffix);
        /**
         * 此处代码有问题 TODO
         */

        try (FileInputStream fis = new FileInputStream(fileName)) {
            OutputStream os = response.getOutputStream();
            byte[] buffer = new byte[1024];
            int offset = 0;
            while((offset = fis.read()) != -1){
                os.write(buffer,0,offset);
            }
        } catch (IOException e) {
            log.error("读取头像失败");
            throw new RuntimeException("读取头像失败",e);
        }
    }


}
